package com.huluobo.a2307douyindemo.mine

import android.content.Intent
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.blankj.utilcode.util.SPUtils
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.google.gson.Gson
import com.huluobo.a2307douyindemo.adapter.CommonPagerAdapter
import com.huluobo.a2307douyindemo.databinding.FragmentMineBinding
import com.huluobo.a2307douyindemo.setting.SettingActivity
import com.huluobo.a2307douyindemo.shop.TabEntity
import com.huluobo.a2307douyindemo.utils.ImageUtils
import com.huluobo.lib_base.bean.UserBean
import com.huluobo.lib_base.event.MessageEvent
import com.huluobo.lib_base.mvvm.BaseFragment
import com.huluobo.lib_base.net.Const

class MineFragment : BaseFragment<FragmentMineBinding, MineViewModel>() {
    private val tabEntities = arrayListOf<CustomTabEntity>()
    private val fragments = mutableListOf<Fragment>()
    private lateinit var commonPagerAdapter: CommonPagerAdapter

    //通过sp获取user对象
    private val userBean = Gson().fromJson(SPUtils.getInstance().getString(Const.KEY_USER), UserBean::class.java)
    override fun initData() {
    }

    override fun initView() {
        ImageUtils.loadImage(requireContext(), userBean.icon, binding.mineUserIconIv)
        binding.mineNicknameTv.text = userBean.nickname

        tabEntities.clear()
        tabEntities.add(TabEntity("喜欢"))
        tabEntities.add(TabEntity("收藏"))
        binding.mineTabLayout.setTabData(tabEntities)

        fragments.clear()
        fragments.add(LikeFragment())
        fragments.add(CollectFragment())

        commonPagerAdapter = CommonPagerAdapter(requireActivity(), fragments)
        binding.mineVp2.adapter = commonPagerAdapter

        binding.mineTabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                binding.mineVp2.currentItem = position
            }

            override fun onTabReselect(position: Int) {
            }
        })

        binding.mineVp2.registerOnPageChangeCallback(object : OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                binding.mineTabLayout.currentTab = position
            }
        })

        binding.mineSettingIv.setOnClickListener {
            val intent = Intent(requireContext(), SettingActivity::class.java)
            startActivity(intent)
        }
    }

    override fun onEvent(messageEvent: MessageEvent) {
        ImageUtils.loadImage(requireContext(), messageEvent.message, binding.mineUserIconIv)
        userBean.icon = messageEvent.message
        SPUtils.getInstance().put(Const.KEY_USER, Gson().toJson(userBean))
    }
}